package com.oocl.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.oocl.pojo.OrderInfo;
import com.oocl.pojo.User;

/**
 * Servlet implementation class AddCartServlet
 */
public class AddCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Logger logger = Logger.getLogger(AddCartServlet.class);

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String bid = request.getParameter("bid");
		String bname= request.getParameter("bname");
		
		Map<String, OrderInfo> carts = (Map<String, OrderInfo>) request.getSession().getAttribute("cart");
		if(null==carts){
			carts = new HashMap<>();
		}
		if(carts.containsKey(bid)){
			OrderInfo info = carts.get(bid);
			int count = info.getCount();
			info.setCount(++count);
		}else {
			OrderInfo info = new OrderInfo();
			info.setBookId(bid);
			info.setBookName(bname);
			info.setCount(1);
			info.setUserId(((User)request.getSession().getAttribute("user")).getId());
			carts.put(bid, info);
		}
		logger.info(((User)request.getSession().getAttribute("user")).getUsername()+" user choose a book "+bname);
		request.getSession().setAttribute("cart", carts);
		request.setAttribute("result", "已加入购物车!");
		request.getRequestDispatcher("store").forward(request, response);
	}

}
